package org.benjamin.lending.service.impl;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by xywen on 2017/5/26.
 */
@Component
public class BasicOperation {

    private final Logger logger = LogManager.getLogger();

    public String sendHttpClient(String url,Map<String,Object> requestMap,String character) throws IOException {
        HttpPost httpPost = new HttpPost(url);
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        Set<String> keySet = requestMap.keySet();
        for(String key : keySet){
            String value = requestMap.get(key).toString();
            nameValuePairs.add(new BasicNameValuePair(key,value));
        }
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs,character));

        HttpClient httpClient = HttpClients.createDefault();
        HttpResponse httpResponse = httpClient.execute(httpPost);

        HttpEntity httpEntity = httpResponse.getEntity();
        String entityBody = EntityUtils.toString(httpEntity);
        if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
            logger.info("请求连接成功发返回的参数：{}",entityBody);
            return entityBody;
        }else{
            logger.error("请求连接失败，返回错误，错误编号是：{}",httpResponse.getStatusLine().getStatusCode());
            logger.error("返回错误信息内容：{}",entityBody);
        }
        return null;
    }
}
